<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jojo 智能助手</title>
    <link rel="stylesheet" href="style.css">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
</head>
<body>
<div class="app-container">
    <!-- 侧边栏 -->
    <div class="sidebar">
        <div class="sidebar-header">
            <button class="new-chat-btn" id="newChatBtn">
                <i class="fas fa-plus"></i>
                新建对话
            </button>
        </div>

        <div class="chat-history" id="chatHistory">
            <div class="history-item active" data-chat-id="default">
                <i class="fas fa-message"></i>
                <span>新对话</span>
                <button class="delete-chat-btn" style="display: none;">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            <!-- 历史对话将通过JS动态加载 -->
        </div>

        <div class="sidebar-footer">
            <div class="user-info">
                <div class="user-avatar">
                    <i class="fas fa-user"></i>
                </div>
                <span class="username">用户</span>
            </div>
            <div class="user-actions">
                <button class="user-action-btn" id="changePasswordBtn" title="修改密码">
                    <i class="fas fa-key"></i>
                </button>
                <button class="user-action-btn" id="logoutBtn" title="退出登录">
                    <i class="fas fa-sign-out-alt"></i>
                </button>
            </div>
        </div>
    </div>

    <!-- 主聊天区域 -->
    <div class="main-content">
        <!-- 聊天消息区域 -->
        <div class="chat-messages" id="chatMessages">
            <div class="welcome-message">
                <div class="welcome-icon">
                    <i class="fas fa-robot"></i>
                </div>
                <h2>你好！我是 jojo</h2>
                <p>很高兴为你服务，请问有什么可以帮助你的？</p>
            </div>
        </div>

        <!-- 输入区域 -->
        <div class="input-container">
            <div class="input-wrapper">
                <div class="text-input-container">
                    <textarea
                            id="messageInput"
                            placeholder="输入你的问题..."
                            rows="1"
                            maxlength="2000"
                    ></textarea>
                    <div class="input-actions">
                        <button id="sendBtn" class="send-btn" disabled>
                            <i class="fas fa-paper-plane"></i>
                        </button>
                    </div>
                </div>
                <div class="input-footer">
                    <span class="char-count">0/2000</span>
                    <div class="quick-actions">
                        <button class="quick-action-btn" data-prompt="帮我写一个简单的Java程序">
                            <i class="fas fa-code"></i> Java
                        </button>
                        <button class="quick-action-btn" data-prompt="解释一下机器学习的基本概念">
                            <i class="fas fa-brain"></i> 机器学习
                        </button>
                        <button class="quick-action-btn" data-prompt="帮我写一个工作总结">
                            <i class="fas fa-file-alt"></i> 工作总结
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 修改密码模态框 -->
<div id="changePasswordModal" class="modal" style="display: none;">
    <div class="modal-content password-modal">
        <div class="modal-header">
            <h3><i class="fas fa-key"></i> 修改密码</h3>
            <button class="close-btn" id="closeChangePasswordModal">&times;</button>
        </div>
        <div class="modal-body">
            <form id="changePasswordForm">
                <div class="form-group">
                    <label for="currentPassword">
                        <i class="fas fa-lock"></i> 原密码
                    </label>
                    <input type="password" id="currentPassword" name="currentPassword" placeholder="请输入当前密码" required>
                </div>
                <div class="form-group">
                    <label for="newPassword">
                        <i class="fas fa-lock-open"></i> 新密码
                    </label>
                    <input type="password" id="newPassword" name="newPassword" placeholder="请输入新密码" required>
                    <div class="password-hint">密码长度至少6位</div>
                </div>
                <div class="form-group">
                    <label for="confirmNewPassword">
                        <i class="fas fa-lock"></i> 确认新密码
                    </label>
                    <input type="password" id="confirmNewPassword" name="confirmNewPassword" placeholder="请再次输入新密码" required>
                </div>
                <div class="form-actions">
                    <button type="button" class="cancel-btn" id="cancelChangePassword">取消</button>
                    <button type="submit" class="confirm-btn">确认修改</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 加载指示器 -->
<div class="typing-indicator" id="typingIndicator" style="display: none;">
    <div class="typing-dots">
        <span></span>
        <span></span>
        <span></span>
    </div>
    <span>Jojo 正在思考...</span>
</div>

<script>
    let currentChatId = 'chat_' + Date.now();
    let isWaitingForResponse = false;
    let chatMessages = [];

    // 从本地存储加载历史对话
    let chatHistory = JSON.parse(localStorage.getItem('chatHistory')) || [];

    // 保存对话历史到本地存储
    function saveChatHistory() {
        localStorage.setItem('chatHistory', JSON.stringify(chatHistory));
    }

    // 更新侧边栏历史对话列表
    function updateChatHistoryList() {
        const chatHistoryDiv = document.getElementById('chatHistory');

        // 清空历史对话列表（保留默认的"新对话"项）
        const defaultItem = chatHistoryDiv.querySelector('.history-item[data-chat-id="default"]');
        chatHistoryDiv.innerHTML = '';
        chatHistoryDiv.appendChild(defaultItem);

        // 添加历史对话项
        chatHistory.forEach(chat => {
            const historyItem = document.createElement('div');
            historyItem.className = 'history-item';
            historyItem.setAttribute('data-chat-id', chat.id);

            // 使用第一条消息作为标题，如果没有则使用默认标题
            const title = chat.messages.length > 0 ?
                (chat.messages[0].content.length > 20 ?
                    chat.messages[0].content.substring(0, 20) + '...' :
                    chat.messages[0].content) :
                '新对话';

            historyItem.innerHTML = `
                <i class="fas fa-message"></i>
                <span class="history-title">${title}</span>
                <button class="delete-chat-btn">
                    <i class="fas fa-times"></i>
                </button>
            `;

            // 添加点击事件
            historyItem.addEventListener('click', function(e) {
                if (!e.target.closest('.delete-chat-btn')) {
                    loadChatHistory(chat.id);
                }
            });

            // 添加删除按钮事件
            const deleteBtn = historyItem.querySelector('.delete-chat-btn');
            deleteBtn.addEventListener('click', function(e) {
                e.stopPropagation();
                deleteChatHistory(chat.id);
            });

            chatHistoryDiv.appendChild(historyItem);
        });

        // 设置当前活跃的对话项
        setActiveChatItem(currentChatId);
    }

    // 设置活跃的对话项
    function setActiveChatItem(chatId) {
        document.querySelectorAll('.history-item').forEach(item => {
            item.classList.remove('active');
        });

        const activeItem = document.querySelector(`.history-item[data-chat-id="${chatId}"]`);
        if (activeItem) {
            activeItem.classList.add('active');
        } else {
            // 如果没有找到对应的历史项，激活默认项
            document.querySelector('.history-item[data-chat-id="default"]').classList.add('active');
        }
    }

    // 加载历史对话
    function loadChatHistory(chatId) {
        const chat = chatHistory.find(c => c.id === chatId);
        if (!chat) return;

        currentChatId = chatId;
        chatMessages = [...chat.messages];

        // 清空聊天区域
        const chatMessagesDiv = document.getElementById('chatMessages');
        chatMessagesDiv.innerHTML = '';

        // 添加历史消息
        chat.messages.forEach(msg => {
            addMessageToChat(msg.role, msg.content, msg.id, false);
        });

        // 设置活跃的对话项
        setActiveChatItem(chatId);

        // 滚动到底部
        scrollToBottom();
    }

    // 删除历史对话
    function deleteChatHistory(chatId) {
        if (confirm('确定要删除这个对话吗？')) {
            chatHistory = chatHistory.filter(chat => chat.id !== chatId);
            saveChatHistory();
            updateChatHistoryList();

            // 如果删除的是当前对话，切换到新对话
            if (currentChatId === chatId) {
                startNewChat();
            }
        }
    }

    // 开始新对话
    function startNewChat() {
        currentChatId = 'chat_' + Date.now();
        chatMessages = [];

        document.getElementById('chatMessages').innerHTML = `
            <div class="welcome-message">
                <div class="welcome-icon">
                    <i class="fas fa-robot"></i>
                </div>
                <h2>新对话已开始</h2>
                <p>我是 Jojo，很高兴为你服务！</p>
            </div>
        `;

        // 设置活跃的对话项
        setActiveChatItem('default');
    }

    // 保存当前对话到历史记录
    function saveCurrentChat() {
        // 如果当前对话没有消息，不保存
        if (chatMessages.length === 0) return;

        // 检查是否已存在
        const existingIndex = chatHistory.findIndex(chat => chat.id === currentChatId);

        if (existingIndex !== -1) {
            // 更新现有对话
            chatHistory[existingIndex].messages = [...chatMessages];
            chatHistory[existingIndex].updatedAt = new Date().toISOString();
        } else {
            // 添加新对话
            chatHistory.unshift({
                id: currentChatId,
                messages: [...chatMessages],
                createdAt: new Date().toISOString(),
                updatedAt: new Date().toISOString()
            });

            // 限制历史记录数量（最多保存50个对话）
            if (chatHistory.length > 50) {
                chatHistory.pop();
            }
        }

        saveChatHistory();
        updateChatHistoryList();
    }

    // 检查登录状态
    function checkLogin() {
        const token = localStorage.getItem('token');
        if (!token) {
            window.location.href = 'login.html';
            return false;
        }
        return true;
    }

    // 生成新的聊天ID
    function generateChatId() {
        return 'chat_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
    }

    // 更新字符计数
    function updateCharCount() {
        const input = document.getElementById('messageInput');
        const charCount = document.querySelector('.char-count');
        charCount.textContent = `${input.value.length}/2000`;
    }

    // 调整输入框高度
    function adjustTextareaHeight() {
        const textarea = document.getElementById('messageInput');
        textarea.style.height = 'auto';
        textarea.style.height = Math.min(textarea.scrollHeight, 120) + 'px';
    }

    // 确保底部间距
    function ensureBottomSpacing() {
        const chatMessagesDiv = document.getElementById('chatMessages');
        const messages = chatMessagesDiv.querySelectorAll('.message');

        if (messages.length > 0) {
            const lastMessage = messages[messages.length - 1];
            lastMessage.style.marginBottom = '20px';
        }
    }

    // 添加消息到聊天界面
    function addMessageToChat(role, content, messageId = null, saveToHistory = true) {
        const chatMessagesDiv = document.getElementById('chatMessages');

        // 如果是第一条消息且正在显示欢迎信息，先清除欢迎信息
        if (chatMessages.length === 0 && chatMessagesDiv.querySelector('.welcome-message')) {
            chatMessagesDiv.innerHTML = '';
        }

        const messageDiv = document.createElement('div');
        messageDiv.className = `message ${role}-message`;
        if (messageId) {
            messageDiv.id = messageId;
        }

        const avatar = role === 'user' ?
            '<i class="fas fa-user"></i>' :
            '<i class="fas fa-robot"></i>';

        const roleName = role === 'user' ? '你' : 'Jojo';
        const currentTime = new Date().toLocaleTimeString('zh-CN', {hour: '2-digit', minute:'2-digit'});

        // 微信风格的消息HTML结构 - 头像在两侧
        messageDiv.innerHTML = `
            <div class="message-content-wrapper">
                <div class="message-avatar ${role}-avatar">
                    ${avatar}
                </div>
                <div class="message-content">
                    <div class="message-header">
                        <span class="message-sender">${roleName}</span>
                        <span class="message-time">${currentTime}</span>
                    </div>
                    <div class="message-text">${formatMessage(content)}</div>
                </div>
            </div>
        `;

        chatMessagesDiv.appendChild(messageDiv);
        scrollToBottom();

        // 保存到消息数组
        const finalMessageId = messageId || Date.now().toString();
        const existingIndex = chatMessages.findIndex(msg => msg.id === finalMessageId);
        if (existingIndex > -1) {
            chatMessages[existingIndex] = { id: finalMessageId, role, content };
        } else {
            chatMessages.push({ id: finalMessageId, role, content });
        }

        // 保存到历史记录
        if (saveToHistory) {
            saveCurrentChat();
        }

        // 确保底部间距
        setTimeout(ensureBottomSpacing, 100);
    }

    // 更新消息内容
    function updateMessageContent(messageId, content) {
        const messageElement = document.getElementById(messageId);
        if (messageElement) {
            const messageText = messageElement.querySelector('.message-text');
            if (messageText) {
                messageText.innerHTML = formatMessage(content);
            }
        }

        // 更新消息数组
        const messageIndex = chatMessages.findIndex(msg => msg.id === messageId);
        if (messageIndex > -1) {
            chatMessages[messageIndex].content = content;
        }

        // 保存到历史记录
        saveCurrentChat();

        // 确保底部间距
        setTimeout(ensureBottomSpacing, 100);
    }

    // 滚动到底部
    function scrollToBottom() {
        const chatMessagesDiv = document.getElementById('chatMessages');
        chatMessagesDiv.scrollTop = chatMessagesDiv.scrollHeight;
    }

    // 显示打字指示器
    function showTypingIndicator() {
        document.getElementById('typingIndicator').style.display = 'flex';
        scrollToBottom();
    }

    // 隐藏打字指示器
    function hideTypingIndicator() {
        document.getElementById('typingIndicator').style.display = 'none';
    }

    // 发送消息
    async function sendMessage() {
        if (!checkLogin() || isWaitingForResponse) return;

        const messageInput = document.getElementById('messageInput');
        const message = messageInput.value.trim();

        if (!message) return;

        // 禁用输入和发送按钮
        isWaitingForResponse = true;
        messageInput.disabled = true;
        document.getElementById('sendBtn').disabled = true;

        // 添加用户消息到界面
        const userMessageId = 'user_' + Date.now();
        addMessageToChat('user', message, userMessageId);

        messageInput.value = '';
        adjustTextareaHeight();
        updateCharCount();

        // 显示打字指示器
        showTypingIndicator();

        try {
            const response = await fetch(`/user/chat?msg=${encodeURIComponent(message)}&chatId=${currentChatId}`, {
                headers: {
                    'token': localStorage.getItem('token')
                }
            });

            if (!response.ok) {
                throw new Error('请求失败');
            }

            const reader = response.body.getReader();
            const decoder = new TextDecoder();

            let fullContent = '';
            const assistantMessageId = 'assistant_' + Date.now();

            // 创建初始的助手消息
            addMessageToChat('assistant', '', assistantMessageId);
            hideTypingIndicator();

            while (true) {
                const { done, value } = await reader.read();
                if (done) break;

                const chunk = decoder.decode(value, { stream: true });
                fullContent += chunk;

                // 更新助手消息内容
                updateMessageContent(assistantMessageId, fullContent);
                scrollToBottom();
            }

        } catch (error) {
            console.error('发送消息失败:', error);
            hideTypingIndicator();
            addMessageToChat('assistant', '抱歉，消息发送失败，请检查网络连接后重试。');
        } finally {
            // 重新启用输入和发送按钮
            isWaitingForResponse = false;
            messageInput.disabled = false;
            document.getElementById('sendBtn').disabled = false;
            messageInput.focus();
        }
    }

    // 格式化消息（简单的Markdown支持）
    function formatMessage(text) {
        if (!text) return '';

        return text
            .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
            .replace(/\*(.*?)\*/g, '<em>$1</em>')
            .replace(/`(.*?)`/g, '<code>$1</code>')
            .replace(/```(\w+)?\n([\s\S]*?)```/g, '<pre><code class="language-$1">$2</code></pre>')
            .replace(/```\n([\s\S]*?)```/g, '<pre><code>$1</code></pre>')
            .replace(/\n/g, '<br>');
    }

    // 修改密码功能
    function initChangePassword() {
        const changePasswordBtn = document.getElementById('changePasswordBtn');
        const changePasswordModal = document.getElementById('changePasswordModal');
        const closeChangePasswordModal = document.getElementById('closeChangePasswordModal');
        const cancelChangePassword = document.getElementById('cancelChangePassword');
        const changePasswordForm = document.getElementById('changePasswordForm');

        // 关闭修改密码模态框的函数
        function closeModal() {
            changePasswordModal.style.display = 'none';
            changePasswordForm.reset();
        }

        // 打开修改密码模态框
        changePasswordBtn.addEventListener('click', function() {
            changePasswordModal.style.display = 'flex';
            document.getElementById('currentPassword').focus();
        });

        // 关闭修改密码模态框 - 关闭按钮
        closeChangePasswordModal.addEventListener('click', closeModal);

        // 关闭修改密码模态框 - 取消按钮
        cancelChangePassword.addEventListener('click', closeModal);

        // 点击模态框外部关闭
        changePasswordModal.addEventListener('click', function(e) {
            if (e.target === changePasswordModal) {
                closeModal();
            }
        });

        // 修改密码表单提交
        changePasswordForm.addEventListener('submit', async function(e) {
            e.preventDefault();

            const currentPassword = document.getElementById('currentPassword').value;
            const newPassword = document.getElementById('newPassword').value;
            const confirmNewPassword = document.getElementById('confirmNewPassword').value;

            // 验证新密码和确认密码是否一致
            if (newPassword !== confirmNewPassword) {
                alert('新密码与确认密码不一致，请重新输入');
                document.getElementById('newPassword').value = '';
                document.getElementById('confirmNewPassword').value = '';
                document.getElementById('newPassword').focus();
                return;
            }

            // 验证密码长度
            if (newPassword.length < 6) {
                alert('新密码长度至少为6位');
                return;
            }

            try {
                const token = localStorage.getItem('token');
                if (!token) {
                    alert('登录已过期，请重新登录');
                    window.location.href = 'login.html';
                    return;
                }

                const response = await fetch('/user/changePassword', {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json',
                        'token': token
                    },
                    body: JSON.stringify({
                        password: currentPassword,
                        newPassword: newPassword
                    })
                });

                const result = await response.json();

                if (result.code === 1) {
                    alert('密码修改成功！请使用新密码重新登录。');

                    // 清除本地存储的token
                    localStorage.removeItem('token');

                    // 关闭模态框
                    closeModal();

                    // 跳转到登录页面
                    setTimeout(() => {
                        window.location.href = 'login.html';
                    }, 1000);
                } else {
                    alert('密码修改失败：' + result.msg);
                }
            } catch (error) {
                console.error('修改密码失败:', error);
                alert('修改密码失败，请检查网络连接后重试');
            }
        });
    }

    // 初始化
    document.addEventListener('DOMContentLoaded', function() {
        if (!checkLogin()) return;

        // 初始化历史对话列表
        updateChatHistoryList();

        // 初始化修改密码功能
        initChangePassword();

        const messageInput = document.getElementById('messageInput');
        const sendBtn = document.getElementById('sendBtn');

        // 输入框事件监听
        messageInput.addEventListener('input', function() {
            updateCharCount();
            adjustTextareaHeight();
            sendBtn.disabled = !this.value.trim();
        });

        messageInput.addEventListener('keydown', function(e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                if (!sendBtn.disabled) {
                    sendMessage();
                }
            }
        });

        messageInput.addEventListener('paste', function(e) {
            setTimeout(() => {
                adjustTextareaHeight();
                updateCharCount();
            }, 0);
        });

        // 发送按钮事件
        sendBtn.addEventListener('click', sendMessage);

        // 新建对话按钮
        document.getElementById('newChatBtn').addEventListener('click', function() {
            startNewChat();
        });

        // 快捷操作按钮
        document.querySelectorAll('.quick-action-btn').forEach(btn => {
            btn.addEventListener('click', function() {
                messageInput.value = this.getAttribute('data-prompt');
                adjustTextareaHeight();
                updateCharCount();
                sendBtn.disabled = false;
                messageInput.focus();
            });
        });

        // 退出登录
        document.getElementById('logoutBtn').addEventListener('click', function() {
            localStorage.removeItem('token');
            window.location.href = 'login.html';
        });

        // 初始调整输入框高度
        adjustTextareaHeight();
        messageInput.focus();
    });
</script>
</body>
</html>